import { getStyle } from "./utils";
export default {
  mounted(el) {
    const oImaWrap = el;
    const oMagWrap = oImaWrap.querySelector(".mag-wrap");
    const oMagImg = oMagWrap.querySelector(".mag-img");
    const imgWidth = getStyle(oImaWrap, "width");
    const imgHeight = getStyle(oImaWrap, "height");
    const magWidth = getStyle(oMagWrap, "width");
    const magHeight = getStyle(oMagWrap, "height");

    const imgX = oImaWrap.offsetLeft;
    const imgY = oImaWrap.offsetTop;

    const init = () => {
      bindEvent();
    };

    function bindEvent() {
      oImaWrap.addEventListener(
        "mouseover",
        function (e) {
          oMagWrap.className += " show";
          showMag(getXY(e));
          document.addEventListener("mousemove", handleMouseMove, false);
          oImaWrap.addEventListener("mouseout", handleMouseOut, false);
        },
        false
      );

      function handleMouseMove(e) {
        showMag(getXY(e));
      }
      function handleMouseOut() {
        oMagWrap.className = "mag-wrap";
        document.removeEventListener("mousemove", handleMouseMove, false);
      }

      function showMag({ x, y, mouseX, mouseY }) {
        oMagWrap.style.left = x + "px";
        oMagWrap.style.top = y + "px";
        oMagImg.style.left = -x + "px";
        oMagImg.style.top = -y + "px";

        if (
          mouseX < 0 ||
          mouseY < 0 ||
          mouseX > imgWidth ||
          mouseY > imgHeight
        ) {
          oMagWrap.className = "mag-wrap";
          document.removeEventListener("mousemove", handleMouseMove, false);
        }
      }

      function getXY(e) {
        return {
          x: e.pageX - imgX - magWidth / 2,
          y: e.pageY - imgY - magHeight / 2,
          mouseX: e.pageX - imgX,
          mouseY: e.pageY - imgY,
        };
      }
    }

    init();
  },
};
